//
//  MyCollectViewController.m
//  yigou
//
//  Created by SunChao on 17/3/7.
//  Copyright © 2017年 hanyiwang. All rights reserved.
//

#import "MyCollectViewController.h"
#import "TribeModel.h"
#import "ContentListCell.h"
#import "ContentListModel.h"
#import "TribeDetailViewController.h"
#import "MyAddTribeListViewController.h"
#import "ArticleWebViewController.h"
#import "TopicleWebViewController.h"

#import "DFLineCellManager.h"
#import "DFBaseLineCell.h"
#import "DFLineLikeItem.h"
#import "DFLineCommentItem.h"
#import "MMPopupWindow.h"
#import "DFLikeCommentView.h"
#import "DyShare.h"

#import "DFImagePreviewViewController.h"

#import "IndexModel.h"
#import "CommentInputView.h"
#define ContentList (@"ContentListCell")

#define sectionHeaderHeight (15)
#define Arc4randomColor [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];

@interface MyCollectViewController ()<UITableViewDelegate,UITableViewDataSource,DFLineCellDelegate, DFImagePreviewViewControllerDelegate, YXCustomActionSheetDelegate>
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *dataSource;

@property (assign, nonatomic) NSInteger page;
@property (assign, nonatomic) BOOL pageToEnd;

@property (nonatomic, strong) NSMutableArray *items;

@property (nonatomic, strong) NSMutableDictionary *itemDic;

@property (nonatomic, strong) NSMutableDictionary *commentDic;

@property (strong, nonatomic) NSString * currentItemId;

@property (nonatomic, strong) UIImagePickerController *pickerController;

@property (strong, nonatomic) NSMutableArray *topicHeights;
@property (strong, nonatomic) CommentInputView *commentInputView;

@end

@implementation MyCollectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.pageToEnd = NO;
    self.page = 1;
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self loadNetworkData];
    [self createUI];
    [self initCommentInputView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [ViewFactory setNavigationBlack:self];
    self.navigationItem.titleView = [ViewFactory makeNavigationTitle:@"我的收藏"];
    UIBarButtonItem *backBtn = [ViewFactory makeNavigationBackWhite:self action:@selector(goPop)];
    self.navigationItem.leftBarButtonItem = backBtn;
    [_commentInputView addNotify];
    [_commentInputView addObserver];
}
//返回
- (void)goPop
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_commentInputView removeNotify];
    
    [_commentInputView removeObserver];
}

-(void) initCommentInputView
{
    if (_commentInputView == nil) {
        _commentInputView = [[CommentInputView alloc] initWithFrame:CGRectMake(0, -64, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _commentInputView.hidden = YES;
        _commentInputView.delegate = self;
        [self.view addSubview:_commentInputView];
    }
    
}
- (void)createUI{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStylePlain];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone ;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:self.tableView];
    [self addRefreshHeader:self.tableView];
    [self addLoadMoreFooter:self.tableView];
    _items = [NSMutableArray array];
    
    _itemDic = [NSMutableDictionary dictionary];
    
    _commentDic = [NSMutableDictionary dictionary];
    
}

#pragma -mark TableView DataSource & Delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    NSDictionary *dic = [self.dataSource objectAtIndex:indexPath.row];
    
    if ([[[dic objectForKey:@"content"] objectForKey:@"content_type"]isEqualToString:@"01"]) {
        return 440;
        
    }else{
        
        NSNumber *height = self.topicHeights[indexPath.row];
        return [height integerValue];
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   NSDictionary *dic = [self.dataSource objectAtIndex:indexPath.row];
    if ([[[dic objectForKey:@"content"] objectForKey:@"content_type"]isEqualToString:@"01"]) {
        ContentListCell *cell = GET_CELL(ContentListCell,@"ContentListCell");
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        [cell contentWithDic:[dic objectForKey:@"content"]];
        [cell hideLikeCommentToolbar];
        return cell;
    }else if ([[[dic objectForKey:@"content"] objectForKey:@"content_type"]isEqualToString:@"00"]){
        DFBaseLineItem *item = [_items objectAtIndex:indexPath.row];
        DFBaseLineCell *typeCell = [self getCell:[item class]];
        NSString *reuseIdentifier = NSStringFromClass([typeCell class]);
        DFBaseLineCell *cell = [tableView dequeueReusableCellWithIdentifier: reuseIdentifier];
        if (cell == nil ) {
            cell = [[[typeCell class] alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        }else{
            NSLog(@"重用Cell: %@", reuseIdentifier);
        }
        
        cell.delegate = self;
        
        cell.separatorInset = UIEdgeInsetsZero;
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            cell.layoutMargins = UIEdgeInsetsZero;
        }
        [cell updateWithItem:item];
        
        return cell;
    }
    return nil;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSource.count;
}




- (void)calculateHeight {
    [self.topicHeights removeAllObjects];
    for(NSInteger i = 0; i < _items.count; i++) {
        DFBaseLineItem *item = [_items objectAtIndex:i];
        DFBaseLineCell *typeCell = [self getCell:[item class]];
        NSInteger height = [typeCell getReuseableCellHeight:item]+40;
        [self.topicHeights addObject:[NSNumber numberWithInteger:height]];
    }
}

- (void)loadNetworkData {
    
   
    DYBaseRequest *request = [DYBaseRequest new];
    NSInteger page = 1;
    NSInteger limit =5;
    ///userCenter/getCollectAllByUserId  我的收藏
    ///userCenter/getContentByUserToLike 赞过的内容
    NSString *url = [NSString stringWithFormat:@"%@/userCenter/getCollectAllByUserId?page=%ld&limit=%ld", APIYIGOU, page,limit];
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        NSDictionary *data = [dict objectForKey:@"data"];
        NSArray *list = [data objectForKey:@"list"];
        
        if (list.count>0) {
            [self hideNoData];
            [self.dataSource removeAllObjects];
            [_items removeAllObjects];
            self.dataSource = [NSMutableArray arrayWithArray:list];
            [self initDataWithArray:self.dataSource];
            [self calculateHeight];
            [self.tableView reloadData];
        }else{
           
                [self showNoData];
        }
        [self.tableView.header endRefreshing];
    } error:^(YTKBaseRequest *request) {
       
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        [self.tableView.header endRefreshing];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        [self.tableView.header endRefreshing];
    }];
}

#pragma mark 上拉、下拉
- (void)refresh {
    [super refresh];
    [self loadNetworkData];
}

- (void)loadMore {
    [super loadMore];
    
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = nil;
    long limit = 5;
    self.page+=1;
    url = [NSString stringWithFormat:@"%@/userCenter/getCollectAllByUserId?page=%ld&limit=%ld", APIYIGOU, self.page,limit];
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        NSDictionary *dataDic = [dict objectForKey:@"data"];
        NSArray *addTopicListArr = [dataDic objectForKey:@"list"];
        
        if (addTopicListArr.count == 0) {
            [ViewFactory showSuccess:@"没有更多数据了！"];
            [self.tableView.footer endRefreshing];
            return ;
        }
        for (NSDictionary *tmpDic in addTopicListArr) {
            [self.dataSource addObject:tmpDic];
        }
        [_items removeAllObjects];
        [self initDataWithArray:self.dataSource];
        [self calculateHeight];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.tableView reloadData];
            [self.tableView.footer endRefreshing];
            
        });
        
    } error:^(YTKBaseRequest *request) {
        [self.tableView.footer endRefreshing];
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        [self.tableView.footer endRefreshing];
    }];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    }
    else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
    [[NSNotificationCenter defaultCenter]postNotificationName:@"HiddenCommentBar" object:nil];
}

#pragma 文章相关方法
- (void)AddCommentDataRequestWithReplyCommentId:(NSString *)replyCommentId ContentId:(NSString *)contentId CommentText:(NSString *)text{
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = @"";
    if (replyCommentId == 0) {
        url = [NSString stringWithFormat:@"%@/hyContent/addComment?content_id=%@&comment=%@", APIYIGOU,contentId,text];
    }else{
        url = [NSString stringWithFormat:@"%@/hyContent/addComment?reply_comment_id=%@&content_id=%@&comment=%@", APIYIGOU,replyCommentId,contentId,text];
    }
    
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        [ViewFactory showSuccess:@"评论成功"];
        [self calculateHeight];
        [self.tableView reloadData];
    } error:^(YTKBaseRequest *request) {
        [self.tableView.footer endRefreshing];
        [ViewFactory showErrorStrMsg:@"评论失败！"];
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        [self.tableView.footer endRefreshing];
    }];
}

//初始化文章数据
-(void) initDataWithArray:(NSArray *)array
{
    
    NSArray *topicArr = array;
    for (NSDictionary *tmpDic in topicArr) {
        NSDictionary *topicDic = [tmpDic objectForKey:@"content"];
        NSLog(@"dic:%@",topicDic);
        DFTextImageLineItem *textImageItem = [[DFTextImageLineItem alloc] init];
        textImageItem.content_id = [topicDic objectForKey:@"content_id"];
        textImageItem.user_id = [topicDic objectForKey:@"user_id"];
        textImageItem.head_url = [[topicDic objectForKey:@"hyUser"] objectForKey:@"head_url"];
        textImageItem.nick_name = [[topicDic objectForKey:@"hyUser"] objectForKey:@"nick_name"];
        textImageItem.title = [topicDic objectForKey:@"title"];
        textImageItem.text = [topicDic objectForKey:@"content_desc"];
        textImageItem.tribe_name = [topicDic objectForKey:@"tribe_name"];
        textImageItem.publish_tm = [topicDic objectForKey:@"publish_tm"];
        textImageItem.content_id = [topicDic objectForKey:@"content_id"];
        textImageItem.tribe_id = [topicDic objectForKey:@"tribe_id"];
        textImageItem.shareUrl = [topicDic objectForKey:@"shareUrl"];
        textImageItem.cover_img = [topicDic objectForKey:@"cover_img"];
        NSArray *picArr = [topicDic objectForKey:@"mediaList"];
        NSMutableArray *srcImages = [NSMutableArray array];
        for (NSDictionary *tmpDic in picArr) {
            NSString *imgString =  [tmpDic objectForKey:@"media_url"];
            [srcImages addObject:imgString];
        }
        [textImageItem.srcImages removeAllObjects];
        
        textImageItem.srcImages = srcImages;
        
        NSArray *contentCmt = [tmpDic objectForKey:@"contentCmtList"];
        
        for (NSDictionary *cmtDic in contentCmt) {
            NSLog(@"cmtArr:%@",cmtDic);
            DFLineCommentItem *commentItem1_1 = [[DFLineCommentItem alloc] init];
            commentItem1_1.commentId = [cmtDic objectForKey:@"comment_id"];
            commentItem1_1.userId = [cmtDic objectForKey:@"user_id"];
            commentItem1_1.userNick = [cmtDic objectForKey:@"user_nike_name"];
            if (![[cmtDic objectForKey:@"reply_user_id"]isEqualToString:@""]) {
                commentItem1_1.replyUserId = [cmtDic objectForKey:@"reply_user_id"];
                commentItem1_1.replyUserNick = [cmtDic objectForKey:@"reply_user_nike_name"];
            }
            
            commentItem1_1.text = [cmtDic objectForKey:@"comment"];
            
            [textImageItem.comments addObject:commentItem1_1];
        }
        
        NSArray *contentLike = [tmpDic objectForKey:@"contentLikeList"];
        [textImageItem.likes removeAllObjects];
        for (NSDictionary *tmpDic in contentLike) {
            DFLineLikeItem *likeItem1_1 = [[DFLineLikeItem alloc] init];
            likeItem1_1.userId = [tmpDic objectForKey:@"user_id"];
            likeItem1_1.userNick = [tmpDic objectForKey:@"nick_name"];
            likeItem1_1.head_url = [tmpDic objectForKey:@"head_url"];
            [textImageItem.likes addObject:likeItem1_1];
        }
        [self addItem:textImageItem];
    }
    
}

#pragma mark - Method

-(DFBaseLineCell *) getCell:(Class)itemClass
{
    DFLineCellManager *manager = [DFLineCellManager sharedInstance];
    return [manager getCell:itemClass];
}

-(void)addItem:(DFBaseLineItem *)item
{
    [self insertItem:item index:_items.count];
}

-(void) addItemTop:(DFBaseLineItem *) item
{
    [self insertItem:item index:0];
}

-(void) insertItem:(DFBaseLineItem *) item index:(NSUInteger)index
{
    [self genCommentAttrString:item];
    
    [_items insertObject:item atIndex:index];
    
    [_itemDic setObject:item forKey:item.content_id];
    
}

-(DFBaseLineItem *) getItem:(NSString *) itemId
{
    return [_itemDic objectForKey:itemId];
    
}

-(void)addCommentItem:(DFLineCommentItem *)commentItem itemId:(NSString *)itemId replyCommentId:(NSString *)replyCommentId

{
    NSString *contentId = itemId;
    NSString *text = commentItem.text;
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = @"";
    if (replyCommentId == 0) {
        url = [NSString stringWithFormat:@"%@/hyContent/addComment?content_id=%@&comment=%@", APIYIGOU,contentId,text];
    }else{
        url = [NSString stringWithFormat:@"%@/hyContent/addComment?reply_comment_id=%@&content_id=%@&comment=%@", APIYIGOU,replyCommentId,contentId,text];
    }
    
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        [ViewFactory showSuccess:@"评论成功"];
        DFBaseLineItem *item = [self getItem:itemId];
        NSMutableArray *tmpArr = [NSMutableArray new];
        [tmpArr addObject:commentItem];
        [tmpArr addObjectsFromArray:item.comments];
        [item.comments removeAllObjects];
        item.comments = tmpArr;
        //[self AddCommentDataRequestWithReplyCommentId:replyCommentId ContentId:itemId CommentText:commentItem.text];
        if (![replyCommentId isEqualToString:@"0"]) {
            DFLineCommentItem *replyCommentItem = [self getCommentItem:replyCommentId];
            
            commentItem.replyUserId = replyCommentItem.userId;
            commentItem.replyUserNick = replyCommentItem.userNick;
            
        }
        
        item.cellHeight = 0;
        [self genCommentAttrString:item];
        [self.tableView reloadData];
    } error:^(YTKBaseRequest *request) {
        [self.tableView.footer endRefreshing];
        [ViewFactory showErrorStrMsg:@"评论失败！"];
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        [self.tableView.footer endRefreshing];
    }];
}

-(void) genCommentAttrString:(DFBaseLineItem *)item
{
    NSMutableArray *comments = item.comments;
    
    [item.commentStrArray removeAllObjects];
    
    for (int i=0; i<comments.count;i++) {
        DFLineCommentItem *comment = [comments objectAtIndex:i];
        [_commentDic setObject:comment forKey:comment.commentId];
        
        NSString *resultStr;
        if (comment.replyUserId == 0) {
            resultStr = [NSString stringWithFormat:@"%@: %@",comment.userNick, comment.text];
        }else{
            resultStr = [NSString stringWithFormat:@"%@回复%@: %@",comment.userNick, comment.replyUserNick, comment.text];
        }
        
        NSMutableAttributedString *commentStr = [[NSMutableAttributedString alloc]initWithString:resultStr];
        if (comment.replyUserId == 0) {
            [commentStr addAttribute:NSLinkAttributeName value:[NSString stringWithFormat:@"%@", comment.userId] range:NSMakeRange(0, comment.userNick.length)];
        }else{
            NSUInteger localPos = 0;
            [commentStr addAttribute:NSLinkAttributeName value:[NSString stringWithFormat:@"%@", comment.userId] range:NSMakeRange(localPos, comment.userNick.length)];
            localPos += comment.userNick.length + 2;
            [commentStr addAttribute:NSLinkAttributeName value:[NSString stringWithFormat:@"%@", comment.replyUserId] range:NSMakeRange(localPos, comment.replyUserNick.length)];
        }
        
        NSLog(@"ffff: %@", resultStr);
        
        [item.commentStrArray addObject:commentStr];
    }
    [self  calculateHeight];
}
-(void)onLike:(NSString *)contentId likeItem:(DFLineLikeItem *)likeItem type:(BOOL)type
{
    //点赞
    if (type) {
        
        DFBaseLineItem *item = [self getItem:contentId];
        NSMutableArray *tmpArr = [NSMutableArray new];
        DFLineLikeItem *likeItem = [[DFLineLikeItem alloc] init];
        likeItem.userId = [UserData userid];
        likeItem.userNick = [UserData username];
        likeItem.head_url = [UserData userheadurl];
        [tmpArr addObject:likeItem];
        [tmpArr addObjectsFromArray:item.likes];
        [item.likes removeAllObjects];
        item.likes = tmpArr;
    }else {
        DFBaseLineItem *item = [self getItem:contentId];
        NSMutableArray *tmpArr = [NSMutableArray new];
        DFLineLikeItem *likeItem = [[DFLineLikeItem alloc] init];
        likeItem.userId = [UserData userid];
        likeItem.userNick = [UserData username];
        likeItem.head_url = [UserData userheadurl];
        [tmpArr addObject:likeItem];
        NSMutableArray *array = [NSMutableArray array];
        for (int i = 0; i<item.likes.count; i++) {
            DFLineLikeItem *tmpItem =  [item.likes objectAtIndex:i];
            if ([tmpItem.userId isEqualToString:likeItem.userId]) {
                //                NSLog(@"有一样的");
                [array addObject:tmpItem];
            }
        }
        [item.likes removeObjectsInArray:array];
    }
    
    [self.tableView reloadData];
}

-(DFLineCommentItem *)getCommentItem:(NSString *)commentId
{
    return [_commentDic objectForKey:commentId];
}



-(void)onComment:(NSString *)itemId
{
    _currentItemId = itemId;
    
    _commentInputView.commentId = @"0";
    
    _commentInputView.hidden = NO;
    
    [_commentInputView show];
}

-(void)onClickComment:(NSString *)commentId itemId:(NSString *)itemId
{
    _currentItemId = itemId;
    
    _commentInputView.hidden = NO;
    
    _commentInputView.commentId = commentId;
    
    [_commentInputView show];
    
    DFLineCommentItem *comment = [_commentDic objectForKey:commentId];
    [_commentInputView setPlaceHolder:[NSString stringWithFormat:@"  回复: %@", comment.userNick]];
}


-(void)onCommentCreate:(NSString *)commentId text:(NSString *)text {
    DFLineCommentItem *commentItem = [[DFLineCommentItem alloc] init];
    commentItem.commentId = commentId;
    commentItem.userId = [UserData userid];
    commentItem.userNick = [UserData username];
    commentItem.text = text;
    [self addCommentItem:commentItem itemId:_currentItemId replyCommentId:commentId];
}

ARRAY_INIT(topicHeights)
ARRAY_INIT(dataSource)
@end

